// 全局变量
let currentMovieId = null;
let currentRating = 0;

$(document).ready(function() {
    // 初始化评分星星点击事件
    $('.rating-star').click(function() {
        const rating = $(this).data('rating');
        setRating(rating);
    });

    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// ==================== 推荐相关函数 ====================

function refreshRecommendations() {
    showLoading();
    location.reload();
}

function viewMovie(movieId) {
    window.location.href = `/movie/${movieId}`;
}

function likeMovie(movieId) {
    $.ajax({
        url: '/api/like_movie',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ movie_id: movieId }),
        success: function(response) {
            if (response.success) {
                showToast('已添加到喜欢列表', 'success');
                // 更新UI，添加视觉反馈
                const card = $(`.movie-card[data-movie-id="${movieId}"]`);
                card.addClass('liked-movie');
                setTimeout(() => card.removeClass('liked-movie'), 2000);
            } else {
                showToast('操作失败', 'error');
            }
        },
        error: function() {
            showToast('网络错误，请重试', 'error');
        }
    });
}

function showRatingModal(movieId) {
    currentMovieId = movieId;
    currentRating = 0;
    resetRatingStars();
    $('#ratingModal').modal('show');
}

function setRating(rating) {
    currentRating = rating;
    $('.rating-star').removeClass('active');
    for (let i = 1; i <= rating; i++) {
        $(`.rating-star[data-rating="${i}"]`).addClass('active');
    }
}

function resetRatingStars() {
    $('.rating-star').removeClass('active');
}

function submitRating() {
    if (currentRating === 0) {
        showToast('请选择评分', 'warning');
        return;
    }

    $.ajax({
        url: '/api/rate_movie',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            movie_id: currentMovieId,
            rating: currentRating
        }),
        success: function(response) {
            if (response.success) {
                showToast('评分已提交', 'success');
                $('#ratingModal').modal('hide');

                // 更新UI
                const card = $(`.movie-card[data-movie-id="${currentMovieId}"]`);
                card.find('.card-footer').append(
                    `<small class="text-success">
                        <i class="fas fa-check me-1"></i>已评分: ${currentRating}星
                    </small>`
                );
            } else {
                showToast('评分失败', 'error');
            }
        },
        error: function() {
            showToast('网络错误，请重试', 'error');
        }
    });
}

function loadRecommendationExplanation() {
    const userId = getCurrentUserId();
    if (!userId) return;

    $.ajax({
        url: `/api/recommendation_explanation/${userId}`,
        method: 'GET',
        success: function(response) {
            $('#explanation-text').text(response.explanation_text);

            // 添加用户类型标签
            const userType = response.user_type;
            const userTypeLabels = {
                'explorer': '探索者',
                'mainstream': '主流用户',
                'early_adopter': '早期采用者',
                'niche_lover': '小众爱好者',
                'balanced': '平衡型'
            };

            const label = userTypeLabels[userType] || userType;
            $('#explanation-text').prepend(
                `<span class="badge bg-primary me-2">${label}</span>`
            );
        },
        error: function() {
            $('#explanation-text').text('基于您的观影历史，我们为您提供了个性化推荐。');
        }
    });
}

// ==================== 管理员仪表板函数 ====================

function loadSystemStats() {
    $.ajax({
        url: '/api/system_stats',
        method: 'GET',
        success: function(data) {
            updateSystemStatsDisplay(data);
        },
        error: function() {
            console.error('Failed to load system stats');
        }
    });
}

function updateSystemStatsDisplay(stats) {
    $('#total-users').text(stats.total_users || 0);
    $('#total-recommendations').text(stats.total_recommendations || 0);
    $('#total-interactions').text(stats.total_interactions || 0);

    // 更新健康状态指示器
    const healthIndicator = $('#health-indicator');
    healthIndicator.removeClass('health-online health-error health-initializing');

    if (stats.system_health === 'Online') {
        healthIndicator.addClass('health-online');
    } else if (stats.system_health.includes('Error')) {
        healthIndicator.addClass('health-error');
    } else {
        healthIndicator.addClass('health-initializing');
    }

    $('#system-health-text').text(stats.system_health);
}

function createPoolDistributionChart(data) {
    const ctx = document.getElementById('poolChart');
    if (!ctx) return;

    // const poolNames = {
    //     'cold_start': '冷启动池',
    //     'test': '测试池',
    //     'growth': '成长池',
    //     'mature': '成熟池',
    //     'long_tail': '长尾池'
    // };

    const labels = Object.keys(data).map(key => poolNames[key] || key);
    const values = Object.values(data);

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: values,
                backgroundColor: [
                    '#17a2b8',
                    '#ffc107',
                    '#28a745',
                    '#007bff',
                    '#dc3545'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

function createUserActivityChart(data) {
    const ctx = document.getElementById('activityChart');
    if (!ctx) return;

    const labels = data.map(item => item.date);
    const values = data.map(item => item.active_users);

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '活跃用户数',
                data: values,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// ==================== 辅助函数 ====================

function getCurrentUserId() {
    // 从页面或session中获取当前用户ID
    return window.currentUserId || null;
}

function showLoading() {
    const loadingHtml = `
        <div class="loading-overlay">
            <div class="loading-spinner"></div>
        </div>
    `;
    $('body').append(loadingHtml);
}

function hideLoading() {
    $('.loading-overlay').remove();
}

function showToast(message, type = 'info') {
    const toastHtml = `
        <div class="toast align-items-center text-white bg-${type === 'error' ? 'danger' : type} border-0" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="fas fa-${getIconForType(type)} me-2"></i>${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;

    let toastContainer = $('#toast-container');
    if (toastContainer.length === 0) {
        toastContainer = $('<div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3"></div>');
        $('body').append(toastContainer);
    }

    const toastElement = $(toastHtml);
    toastContainer.append(toastElement);

    const toast = new bootstrap.Toast(toastElement[0]);
    toast.show();

    // 自动移除
    setTimeout(() => {
        toastElement.remove();
    }, 5000);
}

function getIconForType(type) {
    const icons = {
        'success': 'check-circle',
        'error': 'exclamation-circle',
        'warning': 'exclamation-triangle',
        'info': 'info-circle'
    };
    return icons[type] || 'info-circle';
}

function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    }
    if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

// ==================== 页面特定功能 ====================

// 管理员仪表板特定功能
if (window.location.pathname === '/admin') {
    $(document).ready(function() {
        loadSystemStats();

        // 定期更新统计数据
        setInterval(loadSystemStats, 30000); // 每30秒更新一次
    });
}

// 推荐页面特定功能
if (window.location.pathname === '/recommendations') {
    $(document).ready(function() {
        // 添加动画效果
        $('.movie-card').each(function(index) {
            $(this).css('animation-delay', `${index * 0.1}s`);
            $(this).addClass('fade-in');
        });
    });
}

// 电影详情页特定功能
if (window.location.pathname.includes('/movie/')) {
    $(document).ready(function() {
        // 添加滚动动画
        $(window).scroll(function() {
            $('.similar-movies .movie-card').each(function() {
                const elementTop = $(this).offset().top;
                const elementBottom = elementTop + $(this).outerHeight();
                const viewportTop = $(window).scrollTop();
                const viewportBottom = viewportTop + $(window).height();

                if (elementBottom > viewportTop && elementTop < viewportBottom) {
                    $(this).addClass('fade-in');
                }
            });
        });
    });
}

// ==================== 全局事件监听 ====================

// 处理AJAX错误
$(document).ajaxError(function(event, xhr, settings, thrownError) {
    if (xhr.status === 401) {
        showToast('请先登录', 'warning');
        setTimeout(() => {
            window.location.href = '/login';
        }, 2000);
    } else if (xhr.status === 500) {
        showToast('服务器错误，请稍后重试', 'error');
    }
});

// 处理网络错误
window.addEventListener('online', function() {
    showToast('网络连接已恢复', 'success');
});

window.addEventListener('offline', function() {
    showToast('网络连接已断开', 'warning');
});